//
//  LineLabel.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/14.
//

import UIKit

/// 带中间横线或者下划线的label
public class LineLabel: UILabel {
    /// 横线位置 0-中间 1-底部
    @IBInspectable public var linePosition: UInt = 0
    
    public override func drawText(in rect: CGRect) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = textAlignment
        
        let attributes = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.paragraphStyle: paragraphStyle,
            NSAttributedString.Key.foregroundColor: textColor
        ]
        
        let text = self.text ?? ""
        let textRect = rect.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
        let dashedText = NSMutableAttributedString(string: text)
        dashedText.addAttributes(attributes as [NSAttributedString.Key : Any], range: NSRange(location: 0, length: dashedText.length))
 
        let context = UIGraphicsGetCurrentContext()
        context?.saveGState()
        let points: [CGPoint] = [
            CGPoint(x: textRect.minX, y: linePosition == 1 ? textRect.maxY : textRect.midY),
            CGPoint(x: textRect.maxX, y: linePosition == 1 ? textRect.maxY : textRect.midY)
        ]
        context?.setStrokeColor((textColor.cgColor as CGColor))
        context?.setLineDash(phase: 0, lengths: [2, 0])
        context?.addLines(between: points)
        context?.strokePath()
        dashedText.draw(in: textRect)
        context?.restoreGState()
    }

}
